package com.crealth.thread;


import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.sql.Timestamp;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.apache.log4j.Logger;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;

import com.alibaba.fastjson.JSONObject;
import com.crealth.Config;
import com.crealth.ConstantDefine;
import com.crealth.db.ClienteleDb;
import com.crealth.db.MyselfClienteleDb;
import com.crealth.db.UserDb;
import com.crealth.handler.ResponseMsgQueue;
import com.crealth.model.ClienteleInfoModel;
import com.crealth.model.UserModel;
import com.crealth.msg.NetMessageData;
import com.crealth.utils.PhoneNumDecode;
import com.crealth.utils.Utils;



public class ImportGroupMobiThread extends Thread {
	private static Logger errorLog = Logger.getLogger("error_log");
	
	private String importFileName;
	private boolean needPreUploadData;
	private UserModel userObj;
	private int companyID;
	
	public void setCompanyID(int comID) {
		companyID = comID;
	}
	
	public ImportGroupMobiThread(String fileName, boolean needDel, UserModel user) {
		importFileName = fileName;
		needPreUploadData = needDel;
		userObj = user;
	}
	
	@Override
	public void run() {
		if (needPreUploadData) {
			ClienteleDb.deleteAllGroupCallMobi(userObj.getBelongCompanyID());
		}
		UserDb.updateGroupCallType(companyID, 1);
		
		importMobi();
	}
	
	private void importMobi() {
		int userID = userObj.getId();
		Sheet sheet;
        Workbook book;
        Cell cell2;
        Set<String> mobiGroup = new HashSet<String>();
        try {
        	String strFileName = "./uploadData/" + importFileName;
        	File file = new File(strFileName);
            if(!file.exists()) {
            	return;
            }
            String postfix = Utils.getFileSuffix(importFileName);
            if (postfix.equals("txt")) {
                InputStreamReader read = new InputStreamReader(
                new FileInputStream(file));  //考虑到编码格式
                BufferedReader bufferedReader = new BufferedReader(read);
                String lineTxt = null;
                while((lineTxt = bufferedReader.readLine()) != null){
                	lineTxt = lineTxt.trim();
                	if (lineTxt.length() == 11) {
	            		mobiGroup.add(lineTxt);
	            	}
                }
                read.close();
            } else {        	
	        	InputStream is = new FileInputStream(strFileName);
	            book = WorkbookFactory.create(is);
	            sheet = book.getSheetAt(0);
	            int nCol = 0;           
	            int nRow = 0;
	            boolean hasFinish = false;
	            int rowSum = sheet.getLastRowNum();
	            while(!hasFinish && nRow < rowSum) {
	            	String strValue = "";
	            	Row rowObj = sheet.getRow(nRow);                
	            	cell2 = rowObj.getCell(nCol);
	            	if (cell2 == null) {
	            		continue;
	            	}
	            	strValue = cell2.toString().trim();
	            	if (strValue.startsWith("1.") || strValue.indexOf('E') > 0) {
	            		strValue = ImportClienteleDetailThread.doublePhoneNumToString(strValue);
	            	}
	            	if (strValue.length() == 11) {
	            		mobiGroup.add(strValue);
	            	}	            	
	                nRow++;
	            }
	            book.close();
            }
            
            if (mobiGroup.size() == 0) {
            	return;
            }            
            sendProgressMsg(0, mobiGroup.size());
            String sqlValues = "";
            int idx = 0;
            int belongCompanyID = this.userObj.getBelongCompanyID();
            if (userObj.getPosition() >= ConstantDefine.Head_Manager) {
            	belongCompanyID = companyID;
            }
            long insertTm = System.currentTimeMillis();
            Timestamp tmObj = new Timestamp(insertTm);
            if (userObj.getPosition() >= ConstantDefine.Branch_Mgr_Fu) {
	            for (String mobi : mobiGroup) {            	
	            	if (sqlValues.length() > 0) {
	            		sqlValues += ",";
	            	}
	            	if (Config.mobiPhoneEncrypt) {
	            		mobi = PhoneNumDecode.encryptPhone(mobi);
	            	}
	            	sqlValues += "('" + mobi + "','" + belongCompanyID + "','" + tmObj + "')";
	            	idx++;
	            	if (idx % 100 == 0 || idx == mobiGroup.size()) {
	            		ClienteleDb.insertGroupCallMobi(sqlValues);
	            		sqlValues = "";
	            		sendProgressMsg(idx, mobiGroup.size());
	            	}
	            }
            } else {
            	MyselfClienteleDb.deleteClienteleByCreateID(userID);
            	for (String mobi : mobiGroup) { 
	            	if (Config.mobiPhoneEncrypt) {
	            		mobi = PhoneNumDecode.encryptPhone(mobi);
	            	}
	            	List<ClienteleInfoModel> infols = MyselfClienteleDb.selectClienteleInfoByMobi(mobi, userID);
	            	if (infols == null || infols.size() == 0) {
	            		MyselfClienteleDb.insertClienteleInfo(mobi, "", "", userID);
		            	idx++;
		            	if (idx % 100 == 0 || idx == mobiGroup.size()) {
		            		sendProgressMsg(idx, mobiGroup.size());
		            	}
	            	}
	            }
            }
            
            sendProgressMsg(idx, idx);
            
            Utils.deleteFile(strFileName);
        } catch(Exception e) {
        	errorLog.error("", e);
        }
	}
	
	private void sendProgressMsg(int curNum, int sumNum) {
		NetMessageData sendMsg = new NetMessageData();
		sendMsg.setMsgCmd(NetMessageData.Net_Import_GroupCall_Mobi);
		JSONObject resJson = new JSONObject();
		int userID = userObj.getId();
		resJson.put("resCode", 0);
		resJson.put("curNum", curNum);
		resJson.put("sumNum", sumNum);
        sendMsg.setMsgBody(resJson.toJSONString());
        ResponseMsgQueue.addMsgToQueue(NetMessageData.Net_Import_GroupCall_Mobi, 
        		userID, sendMsg);
	}
	
	
}
